#define latchpin 9 
#define enablepin 10
#define datapin 11
#define clockpin 13

#define iRows 1
#define iCols 11
#define totalLeds iRows * iCols

int iLed[totalLeds][3] = {0};
int mappx[totalLeds] = {10,9,8,7,6,5,4,3,2,1,0};

int r=0, g=0, b=0;
int iCurrLed = 0;

void setup() {

  pinMode(datapin, OUTPUT);
  pinMode(latchpin, OUTPUT);
  pinMode(enablepin, OUTPUT);
  pinMode(clockpin, OUTPUT);

  SPCR = (1<<SPE)|(1<<MSTR)|(0<<SPR1)|(0<<SPR0);

  digitalWrite(latchpin, LOW);
  digitalWrite(enablepin, LOW);

  Serial.begin(57600); 
  Serial.flush();
  
  background(0);
  SB_WriteLEDData();
 
}

void loop() {

  SB_WriteLEDData();
  
  if (nextByte() == 127) {
    iCurrLed = nextByte();
    r = nextByte() << 5 | nextByte();
    g = nextByte() << 5 | nextByte();    
    b = nextByte() << 5 | nextByte();        

    plot(iCurrLed,0,r,g,b); 
  }

  delay(20);

}

byte nextByte() {
  while(1) {
    if(Serial.available() > 0) {
      byte b =  Serial.read();
      return b;
    }
  }
}

void SB_SendPacket(int SB_CommandMode, int r, int g, int b) {

  if (SB_CommandMode == B01) r =  g = b = 127;

  SPDR = SB_CommandMode << 6 | b>>4;
  while(!(SPSR & (1<<SPIF)));

  SPDR = b<<4 | r>>6;
  while(!(SPSR & (1<<SPIF)));

  SPDR = r << 2 | g>>8;
  while(!(SPSR & (1<<SPIF)));

  SPDR = g;
  while(!(SPSR & (1<<SPIF)));

}

void SB_WriteLEDData() {

  for (int f=0; f<totalLeds; f++) SB_SendPacket(B00, iLed[f][0], iLed[f][1], iLed[f][2]);
  delayMicroseconds(15);
  digitalWrite(latchpin,HIGH);
  delayMicroseconds(15);
  digitalWrite(latchpin,LOW);

  for (int f=0; f< totalLeds; f++) SB_SendPacket(B01, 0, 0, 0);
  delayMicroseconds(15);
  digitalWrite(latchpin,HIGH);
  delayMicroseconds(15);
  digitalWrite(latchpin,LOW);

}

void plot(int x, int y, int r, int g, int b){
  iLed[mappx[y*iCols+x]][0] = r;
  iLed[mappx[y*iCols+x]][1] = g;
  iLed[mappx[y*iCols+x]][2] = b;  
}

void background(int c){
  for (int f=0; f<totalLeds; f++){
    iLed[f][0] = iLed[f][1] = iLed[f][2] = c;                       
  }       
}




